package com.xiaoniu.udp;

import io.vertx.core.AbstractVerticle;
import io.vertx.core.Vertx;
import io.vertx.core.datagram.DatagramSocket;
import io.vertx.core.json.JsonObject;

import java.time.LocalDateTime;

/**
 * Created by sweet on 2018/1/2.
 * ---------------------------
 */
public class UdpServerVerticle extends AbstractVerticle {
    public static void main(String[] args) {
        Vertx.vertx().deployVerticle(new UdpServerVerticle());
    }

    @Override
    public void start() throws Exception {
        final DatagramSocket server = vertx.createDatagramSocket();

        server.listen(8080, "127.0.0.1", h -> {
           if (h.succeeded()) {
               DatagramSocket result = h.result();
               result.handler(socket -> {
                   String s = socket.data().toString();
                   System.out.println("Server 收到消息：" + s);
                   String host = socket.sender().host();
                   int port = socket.sender().port();
                   String path = socket.sender().path();
                   System.out.println("host: " + host+", port: " + port + ", path: " + path);
                   JsonObject jsonObject = new JsonObject()
                       .put("host", host).put("port", port).put("msg", "Hello world Im Server");
                   vertx.eventBus().send(this.getClass().getName()+"Sender", jsonObject, res -> {
                      if (res.succeeded()) {
                          System.out.println("server 发送给客户端 " + res.result().body().toString() + "\n");
                      } else {
                          res.cause().printStackTrace();
                      }
                   });

               });
           } else {
               h.cause().printStackTrace();
           }
        });

        vertx.eventBus().<JsonObject>consumer(this.getClass().getName()+"Sender", msg -> {

            JsonObject body = msg.body();
            Integer port = body.getInteger("port");
            String host = body.getString("host");
            String msg1 = body.getString("msg");

            server.send(msg1, port, host, res -> {
                if (res.succeeded()) {
                    msg.reply("OK");
                } else {
                    res.cause().printStackTrace();
                    msg.reply("ERROR");
                }
            });
        });
    }
}
